package com.apes.fn.server.servicePlan.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.business.fixedLoss.repository.LossQuotationRepository;
import com.apes.fn.crm.customer.FnAppCustomerService;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.crm.customerExpand.FnCustomerExpandRepository;
import com.apes.fn.mdm.purchase.PurchasingGroupRepository;
import com.apes.fn.pi.fnCommunal.FnCommunalService;
import com.apes.fn.scm.merchant.settlement.service.FeeRateService;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.fn.supp.model.SantouChannel;
import com.apes.fn.supp.repository.SantouChannelRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.soe.store.database.repository.BusinessAttributeValueRepository;
import com.apes.framework.util.Arith;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.car.model.CarServiceLevel;
import com.apes.scm.masterdata.car.service.CarServiceLevelService;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.service.StoreService;
import com.apes.scm.masterdata.party.model.Corporate;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.AccessProviderRepository;
import com.apes.scm.masterdata.party.repository.CorporateRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Category;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.CategoryRepository;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.product.repository.ServeTypeRepository;
import com.apes.scm.masterdata.product.service.ProductService;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.service.LocationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 类描述：
 *
 * @ClassName PriceService
 * @Description 描述
 * @Author wushilong
 * @Date 2023/2/10 11:10
 * @Version 1.0
 */
@Service
public class PriceForwardService extends DomainService {

    private String platform = "";

    private Map<String, Double> spProductMap;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ServiceToForeign serviceToForeign;

    @Autowired
    private DeptRepository deptRepository;

    @Autowired
    private FnCommunalService fnCommunalService;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private CorporateRepository corporateRepository;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PartyRoleRepository partyRoleRepository;
    /**
     * 商品前置价格展示
     *
     * @param request 请求对象
     * @return
     */
    public Map queryPriceForward(SimpleRequest request) {
        JSONObject param = request.getJO();
        JSONArray condition = param.getJSONArray("condition");
        JSONObject conditionModel = param.getJSONObject("conditionModel");
        String id = "";
        if (Objects.nonNull(conditionModel.getJSONObject("fixedLossDept"))) {
            id = conditionModel.getJSONObject("fixedLossDept").getString("id");
        }
        if (Objects.nonNull(conditionModel.getJSONObject("belongDept"))) {
            id = conditionModel.getJSONObject("belongDept").getString("id");
        }
        //没有门店无查询价格前置商品
        if ("".equals(id)) return new HashMap();
        Dept dept = deptRepository.findOne(id);

        String categoryId = "";//配件名称ID
        String PZCXID = "";//车型配置ID
        //获取查询条件
        for (Object o : condition) {
            JSONObject item = (JSONObject) o;
            if ("dataCenterCondition".equals(item.getString("field")))
                PZCXID = item.getJSONObject("value").getString("PZCXID");
            if ("searchContent".equals(item.getString("field")))
                categoryId = item.getJSONObject("value").getString("partsTagId");
        }

        //根据配置车型ID+标准名称匹配商品
        if (StringUtils.isEmpty(categoryId) || StringUtils.isEmpty(PZCXID))
            return MapUtil.mapper("type", "Whole", "content", new ArrayList<>());
        JSONObject json = JSON.parseObject(invoke("sp.matching.meaningfulProduct", MapUtil.mapper("category", categoryId, "PZCXID", PZCXID)));
        JSONArray body = json.getJSONArray("body");

        //赋能扩展表
        FnCustomerExpand fnCustomerExpand = getFnCustomerExpand(conditionModel);


        spProductMap = new HashMap<>();
        this.platform = "zt";

        body = supplierGroup(body, dept);
        return getResult(body, dept, fnCustomerExpand);
    }

    /**
     * 获取赋能扩展表信息
     * @return
     */
    private FnCustomerExpand getFnCustomerExpand(JSONObject conditionModel) {
        FnCustomerExpand fnCustomerExpand = new FnCustomerExpand();
        if (Objects.isNull(conditionModel.getJSONObject("fnCustomerExpandTemp"))) {
            String carLiscence = conditionModel.getString("carLiscence");
            fnCustomerExpand = getFnCustomerExpand(carLiscence, "");
        } else {
            fnCustomerExpand = JSON.parseObject(conditionModel.getJSONObject("fnCustomerExpandTemp").toJSONString(), FnCustomerExpand.class);
        }
        return fnCustomerExpand;
    }

    //根据采购组过滤供应商
    private JSONArray supplierGroup(JSONArray body, Dept dept){
        //根据采购组确定供应商
        List<String> suppliers = getBean(PurchasingGroupRepository.class).accordingToDeptGetSupplierId(dept.getId());
        return body.stream().filter(o -> {
            JSONObject item = (JSONObject) o;
            if (Objects.isNull(item.getJSONObject("product")) || Objects.isNull(item.getJSONObject("product").getJSONObject("supplier"))) return false;
            return suppliers.contains(item.getJSONObject("product").getJSONObject("supplier").getString("id"));
        }).collect(Collectors.toCollection(JSONArray::new));
    }

    /**
     * 获取赋能扩展表信息
     * @param carLicense
     * @param vendorCode String accessProvider = SpringManager.getBean(AccessProviderRepository.class).findByCompany(dept.getCompany().getId()).getId();//接入商
     * @return
     */
    public FnCustomerExpand getFnCustomerExpand(String carLicense, String vendorCode) {

        List<FnCustomerExpand> fnCustomerExpands = getBean(FnCustomerExpandRepository.class).findAllByCarLicenseAndVendorCode(carLicense, vendorCode);
        FnCustomerExpand getMeetCondiFnCustomer = fnCustomerExpands.stream().filter(item -> StringUtils.isNotEmpty(item.getJekunModelCode())).findFirst().orElse(null);
        if (getMeetCondiFnCustomer != null) return getMeetCondiFnCustomer;

        JSONObject request = new JSONObject();
        JSONObject carLicenseParam = new JSONObject();
        carLicenseParam.put("field", "carLicense");
        carLicenseParam.put("value", carLicense);
        carLicenseParam.put("operator", "EQ");
        JSONObject ven = new JSONObject();
        ven.put("field", "ven");
        ven.put("value", "ven");
        ven.put("operator", "EQ");

        request.put("condition", Arrays.asList(carLicenseParam, ven));
        request.put("size", 20);
        request.put("page", 0);
        SimpleRequest simpleRequest = new SimpleRequest();
        simpleRequest.setData(request);
        Map allCustomerCar = getBean(FnAppCustomerService.class).findAllCustomerCar(simpleRequest);
        JSONArray content = (JSONArray) allCustomerCar.get("content");
        JSONObject customer = (JSONObject) content.stream().filter(item-> StringUtils.isNotEmpty(((JSONObject)item).getString("vin"))).findFirst().get();
        FnCustomerExpand fnCustomerExpand = JSON.parseObject(customer.toJSONString(), FnCustomerExpand.class);
        return fnCustomerExpand;
    }


    /**
     * 按标准名称分类商品
     * products: [{"product":"商品主属性","extend":"商品扩展属性"},{"product":"商品主属性","extend":"商品扩展属性"},...]
     *
     * @param products
     * @return
     */
    private Map getResult(JSONArray products, Dept dept, FnCustomerExpand fnCustomerExpand) {
        if (products.isEmpty()) return MapUtil.mapper("type", "Whole", "content", new ArrayList<>());
        JSONObject one = (JSONObject) products.stream().findAny().get();
        //根据标准商品类型分发
        switch (one.getJSONObject("product").getString("standardType")) {
            case "Accumulator":
                return accumulator(products, fnCustomerExpand, dept);//蓄电池
            case "Tyre":
                return tyre(products, fnCustomerExpand, dept);//轮胎
            case "Oily":
                return oily(products, fnCustomerExpand, dept);//机油
        }

        return whole(products, fnCustomerExpand, dept);//全车件
    }

    //全车件商品价格前置
    private Map whole(JSONArray products, FnCustomerExpand fnCustomerExpand, Dept dept) {
        List showProducts = new ArrayList<>();
        products.stream().forEach( o -> {
            JSONObject item = (JSONObject) o;
            JSONObject product = item.getJSONObject("product");
            JSONObject supplier = product.getJSONObject("supplier");//供应商
            Double priceSuggested = 0.00;//建议售价
            JSONObject category = product.getJSONObject("category");
            Double notTaxUnitPrice = 0.00;
            double taxUnitPrice = 0.00;
            JSONObject quoteResult = item.getJSONObject("quoteResult");
            if (quoteResult != null) {
                notTaxUnitPrice = quoteResult.getDouble("notTaxUnitPrice");
                taxUnitPrice = quoteResult.getDoubleValue("taxUnitPrice");
            } else {
                notTaxUnitPrice = product.getDouble("notTaxUnitPrice");
            }
            String classify = Objects.isNull(category) ? "M01030501001" : categoryRepository.findOne(category.getString("id")).getClassify().getId();
            //根据品牌+零件号获取标准商品
            JSONObject response = JSON.parseObject(invoke("dc.brandProduct.getBrandProduct", MapUtil.mapper("brand", product.getJSONObject("spBrand").getString("name"),
                    "brandMark", product.getString("OE"))));
            JSONObject autoWhole = response.getJSONObject("body");

            //成本价是否加票点
            if (taxUnitPrice == 0.0) {
                taxUnitPrice = getNotTaxUnitPrice(dept, product, supplier, classify, notTaxUnitPrice);
            }
            //获取销售价格
            priceSuggested = getPriceSuggested(dept, fnCustomerExpand, product, autoWhole, priceSuggested, notTaxUnitPrice, classify);

            //最终结果
            JSONObject showProduct = new JSONObject();
            getResult(fnCustomerExpand, dept, showProduct, item, product, taxUnitPrice, supplier, priceSuggested, category, notTaxUnitPrice, classify, autoWhole);
            showProducts.add(showProduct);
        });
        return MapUtil.mapper("type", "Whole", "content", showProducts);
    }

    private void getResult(FnCustomerExpand fnCustomerExpand, Dept dept, JSONObject showProduct, JSONObject item, JSONObject product, double taxUnitPrice,
                           JSONObject supplier, Double priceSuggested, JSONObject category, Double notTaxUnitPrice, String classify, JSONObject autoWhole) {
        //用于前端展示的数据
        if (Objects.nonNull(item.getJSONObject("category"))) {
            showProduct.put("category", item.getJSONObject("category").getString("name"));//标准名称
        }
        if(!Objects.nonNull(product.getJSONObject("category"))&& Objects.nonNull(product.getJSONObject("transientCategory"))) {
            showProduct.put("category", product.getJSONObject("transientCategory").getString("name"));//标准名称
        }
        showProduct.put("id", product.getString("id"));//供应商平台商品id
        showProduct.put("spProduct", product);//商品
        showProduct.put("name", product.getString("name"));//商品名称
        showProduct.put("spBrand", item.getJSONObject("brand"));//品牌
        showProduct.put("pn", product.getString("OE"));//零件号
        showProduct.put("describe", product.getString("describe"));//产品描述
        showProduct.put("notTaxUnitPrice", taxUnitPrice);//成本价
        showProduct.put("nakedPrice", notTaxUnitPrice);//裸价
        showProduct.put("priceSuggested", priceSuggested);//建议售价
        showProduct.put("supplier", supplierSimple(supplier.getString("id")));//供应商
        showProduct.put("OE", product.getString("OE"));//零件号
        showProduct.put("standardType", product.getString("standardType"));//标准商品类型
        showProduct.put("fitting", Objects.isNull(category) ? MapUtil.mapped(categoryRepository.findOne("013951")) : category);//配件
        showProduct.put("resultJsonReback", getRetailPrice(dept, fnCustomerExpand, autoWhole));//销售51
        showProduct.put("classify", classify);//品类编码
        showProduct.put("sale", getSale(notTaxUnitPrice, product, classify));//加价规则
        showProduct.put("auoteResult", item.getString("auoteResult"));//报价ID
        showProduct.put("enquiry", item.getString("enquiry"));//询价单ID
        showProduct.put("fourSPrice", item.getString("fourSPrice"));//询价单ID
        showProduct.put("productRule", item.getBoolean("productRule"));
        if (item.getString("quoteResult") != null) {
            JSONObject jo = item.getJSONObject("quoteResult");
            showProduct.put("note", jo.getString("note"));//备注
            if (jo.getString("placeOfDispatch") != null && jo.getInteger("placeOfDispatch") > 0) {
                showProduct.put("state", "订货" + jo.getInteger("placeOfDispatch") + "天数");//订货状态
            } else {
                showProduct.put("state", "现货");//订货状态
            }
            if (Objects.nonNull(jo.getJSONArray("transientPicture")) && jo.getJSONArray("transientPicture").size() > 0) {
                showProduct.put("png", jo.getJSONArray("transientPicture").toString());//图片
            }
            showProduct.put("productName", item.getJSONObject("category").getString("name"));//待报价配件名称
            showProduct.put("OE", jo.getJSONObject("product").getString("OE"));//报价零件号
            showProduct.put("address", item.getString("address"));//发货地
        }
        if (Objects.nonNull(autoWhole) && StringUtils.isNotEmpty(autoWhole.getString("ERPProductId"))){
            showProduct.put("ERPProduct", autoWhole.getString("ERPProductId"));
        }
        showProduct.put("quoteResult", item.getJSONObject("quoteResult"));//报价结果
        showProduct.put("quoteResultId", item.getString("quoteResultId"));//报价单ID
    }

    /**
     * 根据门店判断成本价是否加票点
     * @param dept 门店
     * @param product 商品
     * @param supplier 供应商
     * @param classify 品类
     * @param notTaxUnitPrice 不含税单价
     * @return
     */
    private double getNotTaxUnitPrice(Dept dept, JSONObject product, JSONObject supplier, String classify, Double notTaxUnitPrice){
        List<BusinessParam> businessParams = getBean(BusinessParamRepository.class).accordingToCompanyContract(Arrays.asList(dept.getCompany().getId()));
        double supplierTicketPoint = 0.0;
        if (businessParams.size() > 0) {
            BusinessParam businessParam = businessParams.get(0);
            String condition = businessParam.getValue();
            Corporate corporate = corporateRepository.findByPartyRole(condition);
            if (corporate != null && !corporate.getTaxpayer().getCode().equals("02")) {
                supplierTicketPoint = getSupplierTicketPoint(dept.getCompany().getId(), supplier.getString("id"), product.getJSONObject("spBrand").getString("id"), classify);//票点
            }
        } else {
            //获取供应商票点
            Corporate corporate = dept.getCompany().getParty().getCorporate();
            if (corporate != null && !corporate.getTaxpayer().getCode().equals("02")) {
                supplierTicketPoint = getSupplierTicketPoint(dept.getCompany().getId(), supplier.getString("id"), product.getJSONObject("spBrand").getString("id"), classify);//票点
            }
        }
        return Double.parseDouble(twoDecimalPlaces(notTaxUnitPrice * (supplierTicketPoint / 100 + 1.0)));
    }

    /**
     * 获取销售价格
     * @param dept 门店
     * @param fnCustomerExpand 客户信息
     * @param product 商品
     * @param autoWhole 扩展信息
     * @param priceSuggested 销售价格
     * @param notTaxUnitPrice 成本价
     * @param classify 品类
     * @return
     */
    private double getPriceSuggested(Dept dept, FnCustomerExpand fnCustomerExpand, JSONObject product,JSONObject autoWhole,
                                     double priceSuggested, double notTaxUnitPrice, String classify){

        //判断是否维护ERP商品ID，如果未维护标准商品的ERP商品编码则不对照，走价格规则
        JSONObject retailPrice = getRetailPrice(dept, fnCustomerExpand, autoWhole);

        //建议售价
        priceSuggested = retailPrice.isEmpty() ? 0.0 : retailPrice.getDouble("primaryPriceUnit");

        //没有价格文件则走加价规则
        if (priceSuggested == 0.0) {
            //根据采购加价规则获取建议售价
            JSONObject sale = getSale(notTaxUnitPrice, product, classify);
            //建议售价
            priceSuggested = sale.getDouble("XSDJ");
        }

        //保留两位小数
        return Double.parseDouble(twoDecimalPlacesRound(priceSuggested));
    }

    //判断是否维护ERP商品ID，如果未维护标准商品的ERP商品编码则不对照，走价格规则
    private JSONObject getRetailPrice(Dept dept, FnCustomerExpand fnCustomerExpand, JSONObject autoWhole) {

        if (Objects.nonNull(autoWhole) && StringUtils.isNotEmpty(autoWhole.getString("ERPProductId"))) {
            Product erpProduct = productRepository.findOne(autoWhole.getString("ERPProductId"));
            if (erpProduct != null) {
                String price = (String) stringRedisTemplate.opsForHash().get("retailPrice", dept.getId() + fnCustomerExpand.getCarLicense()
                        + autoWhole.getString("ERPProductId"));
                if (StringUtils.isNotEmpty(price)){
                    return JSONObject.parseObject(price);
                }
                JSONObject retailPrice = getRetailPrice(fnCustomerExpand, erpProduct, dept);
                stringRedisTemplate.opsForHash().put("retailPrice",dept.getId() + fnCustomerExpand.getCarLicense() + autoWhole.getString("ERPProductId"),
                        retailPrice.toJSONString());
                stringRedisTemplate.expire("retailPrice", 3 , TimeUnit.DAYS);
                return getRetailPrice(fnCustomerExpand, erpProduct, dept);
            }
        }
        return new JSONObject();
    }

    //根据采购加价规则获取建议售价
    private JSONObject getSale(double notTaxUnitPrice, JSONObject product, String classify){
        String price = (String) stringRedisTemplate.opsForHash().get("retailPrice", product.getString("id") + "/" + notTaxUnitPrice);
        if (StringUtils.isNotEmpty(price)){
            return JSONObject.parseObject(price);
        }
        JSONObject sale = invoke("scm.externalInquiry.newSystemPrice", MapUtil.mapper("P001", notTaxUnitPrice,
                "CLASSIFY_ID", classify, "BRAND_ID", product.getJSONObject("spBrand").getString("id"), "SYS_RQ", new Date()));
        stringRedisTemplate.opsForHash().put("retailPrice",product.getString("id") + "/" + notTaxUnitPrice, sale.toJSONString());
        stringRedisTemplate.expire("retailPrice", 3 , TimeUnit.DAYS);
        if (stringRedisTemplate.opsForHash().size("retailPrice") >= 30000){
            stringRedisTemplate.delete("retailPrice");
        }
        return sale;
    }

    //蓄电池商品价格前置
    private Map accumulator(JSONArray products, FnCustomerExpand fnCustomerExpand, Dept dept) {
        List showProducts = new ArrayList<>();
        for (Object o : products) {
            JSONObject item = (JSONObject) o;
            JSONObject product = item.getJSONObject("product");
            JSONObject accumulator = item.getJSONObject("extend");//扩展信息
            JSONObject supplier = product.getJSONObject("supplier");//供应商
            Double priceSuggested = 0.0;//建议售价
            Double notTaxUnitPrice = 0.0;
            double taxUnitPrice = 0.0;
            JSONObject quoteResult = item.getJSONObject("quoteResult");
            if (quoteResult != null) {
                notTaxUnitPrice = quoteResult.getDouble("notTaxUnitPrice");
                taxUnitPrice = quoteResult.getDoubleValue("taxUnitPrice");
            } else {
                notTaxUnitPrice = product.getDouble("notTaxUnitPrice");
            }
            JSONObject category = product.getJSONObject("category");
            String classify = Objects.isNull(category) ? "M01010105001" : categoryRepository.findOne(category.getString("id")).getClassify().getId();

            //通过品牌+国际标号+参考号获取蓄电池标准商品
            JSONObject response = JSON.parseObject(invoke("dc.accumulatorProduct.getAccumulatorProduct",
                    MapUtil.mapper("brand", product.getJSONObject("spBrand").getString("name"),
                            "grade", accumulator.getString("international"), "reference", accumulator.getString("reference"))));
            JSONObject autoAccumulator = response.getJSONObject("body");

            //是否加票点
            if (taxUnitPrice == 0.0) {
                taxUnitPrice = getNotTaxUnitPrice(dept, product, supplier, classify, notTaxUnitPrice);
            }

            //获取销售价格
            priceSuggested = getPriceSuggested(dept, fnCustomerExpand, product, autoAccumulator, priceSuggested, notTaxUnitPrice, classify);

            //老系统扩展表数据
            product.put("extend", extend(accumulator, "Accumulator"));
            accumulator.remove("id");
            product.putAll(accumulator);//将扩展信息和主属性合在一起

            //最终结果
            JSONObject showProduct = new JSONObject();
            getResult(fnCustomerExpand, dept, showProduct, item, product, taxUnitPrice, supplier, priceSuggested, category, notTaxUnitPrice, classify, autoAccumulator);

            //用于前端展示的数据
            showProduct.put("international", accumulator.getString("international"));//国际标号
            showProduct.put("reference", accumulator.getString("reference"));//参考号
            showProduct.put("fitting", Objects.isNull(category) ? MapUtil.mapped(categoryRepository.findOne("000618")) : category);//配件
            showProduct.put("classify", classify);//品类编码
            showProducts.add(showProduct);
        }
        return MapUtil.mapper("type", "Accumulator", "content", showProducts);
    }

    //轮胎商品价格前置
    private Map tyre(JSONArray products, FnCustomerExpand fnCustomerExpand, Dept dept) {
        List showProducts = new ArrayList<>();
        for (Object o : products) {
            JSONObject item = (JSONObject) o;
            JSONObject product = item.getJSONObject("product");
            JSONObject tyre = item.getJSONObject("extend");//扩展信息
            JSONObject supplier = product.getJSONObject("supplier");//供应商
            Double priceSuggested = 0.0;//建议售价
            JSONObject category = product.getJSONObject("category");
            Double notTaxUnitPrice = 0.0;
            double taxUnitPrice = 0.0;
            JSONObject quoteResult = item.getJSONObject("quoteResult");
            if (quoteResult != null) {
                notTaxUnitPrice = quoteResult.getDouble("notTaxUnitPrice");
                taxUnitPrice = quoteResult.getDoubleValue("taxUnitPrice");
            } else {
                notTaxUnitPrice = product.getDouble("notTaxUnitPrice");
            }
            String classify = Objects.isNull(category) ? "M01010102001" : categoryRepository.findOne(category.getString("id")).getClassify().getId();

            //根据品牌+规格+花纹+载重指数+速度等级+是否防爆获取单个轮胎标准商品
            JSONObject response = JSON.parseObject(invoke("dc.tyreProduct.getTyreProduct", MapUtil.mapper("brand", product.getJSONObject("spBrand").getString("name"),
                    "specification", tyre.getString("specification"), "figure", tyre.getString("figure"), "loadIndex", tyre.getString("loadIndex"),
                    "speedClass", tyre.getString("speedClass"), "antiExplosion", tyre.getString("antiExplosion"))));
            JSONArray body = response.getJSONArray("body");
            JSONObject autoTyre = body.isEmpty() ? null : (JSONObject)body.stream().findFirst().get();
            JSONObject retailPrice = null;
            JSONObject sale = null;

            //是否加票点
            if (taxUnitPrice == 0.0) {
                taxUnitPrice = getNotTaxUnitPrice(dept, product, supplier, classify, notTaxUnitPrice);
            }

            //获取销售价格
            priceSuggested = getPriceSuggested(dept, fnCustomerExpand, product, autoTyre, priceSuggested, notTaxUnitPrice, classify);

            //老系统扩展表数据
            product.put("extend", extend(tyre, "Tyre"));
            tyre.remove("id");
            product.putAll(tyre);//将扩展信息和主属性合在一起

            //最终结果
            JSONObject showProduct = new JSONObject();
            getResult(fnCustomerExpand, dept, showProduct, item, product, taxUnitPrice, supplier, priceSuggested, category, notTaxUnitPrice, classify, autoTyre);

            //用于前端展示的数据
            showProduct.put("specification", tyre.getString("specification"));//规格
            showProduct.put("figure", tyre.getString("figure"));//花纹
            showProduct.put("loadIndex", tyre.getString("loadIndex"));//载重指数
            showProduct.put("speedClass", tyre.getString("speedClass"));//速度等级
            showProduct.put("antiExplosion", tyre.getBoolean("antiExplosion") ? "是" : "否");//是否防爆
            showProduct.put("fitting", Objects.isNull(category) ? MapUtil.mapped(categoryRepository.findOne("000609")) : category);//配件
            showProduct.put("autoName", partName(showProduct));//商品名称
            showProducts.add(showProduct);
        }
        return MapUtil.mapper("type", "Tyre", "content", showProducts);
    }

    //机油商品价格前置
    private Map oily(JSONArray products, FnCustomerExpand fnCustomerExpand, Dept dept) {
        List showProducts = new ArrayList<>();
        for (Object o : products) {
            JSONObject item = (JSONObject) o;
            JSONObject product = item.getJSONObject("product");
            JSONObject oily = item.getJSONObject("extend");//扩展信息
            JSONObject supplier = product.getJSONObject("supplier");//供应商
            Double priceSuggested = 0.0;//建议售价
            Double notTaxUnitPrice = 0.0;
            double taxUnitPrice = 0.0;
            JSONObject quoteResult = item.getJSONObject("quoteResult");
            if (quoteResult != null) {
                notTaxUnitPrice = quoteResult.getDouble("notTaxUnitPrice");
                taxUnitPrice = quoteResult.getDoubleValue("taxUnitPrice");
            } else {
                notTaxUnitPrice = product.getDouble("notTaxUnitPrice");
            }
            JSONObject category = product.getJSONObject("category");
            String classify = Objects.isNull(category) ? "M01010201009" : categoryRepository.findOne(category.getString("id")).getClassify().getId();

            //根据品牌+粘度等级+api类型+类型+容量获取机油类标准商品商品
            JSONObject response = JSON.parseObject(invoke("cm.oilyProduct.getOilyProduct", MapUtil.mapper("brand", product.getJSONObject("spBrand").getString("name"),
                    "viscosityClass", oily.getString("viscosityClass"), "apiClass", oily.getString("apiClass"), "type", oily.getString("type"), "capacity", oily.getString("capacity"))));
            JSONObject autoOily = response.getJSONObject("body");

            //是否加票点
            if (taxUnitPrice == 0.0) {
                taxUnitPrice = getNotTaxUnitPrice(dept, product, supplier, classify, notTaxUnitPrice);
            }

            //获取销售价格
            priceSuggested = getPriceSuggested(dept, fnCustomerExpand, product, autoOily, priceSuggested, notTaxUnitPrice, classify);

            oily.remove("id");
            product.putAll(oily);//将扩展信息和主属性合在一起

            //最终结果
            JSONObject showProduct = new JSONObject();
            getResult(fnCustomerExpand, dept, showProduct, item, product, taxUnitPrice, supplier, priceSuggested, category, notTaxUnitPrice, classify, autoOily);

            //用于前端展示的数据
            showProduct.put("viscosityClass", oily.getString("viscosityClass"));//粘度等级
            showProduct.put("apiClass", oily.getString("apiClass"));//API等级
            showProduct.put("type", oily.getString("type"));//机油类型
            showProduct.put("catena", oily.getString("catena"));//系列
            showProduct.put("capacity", oily.getString("capacity"));//容量
            showProduct.put("fitting", Objects.isNull(category) ? MapUtil.mapped(categoryRepository.findOne("000678")) : category);//配件
            showProducts.add(showProduct);
        }
        return MapUtil.mapper("type", "Oily", "content", showProducts);
    }

    /**
     * 供应商简称
     *
     * @param supplier
     * @return
     */
    private String supplierSimple(String supplier) {
        PartyRole supplierPartyRole = partyRoleRepository.findOne(supplier);
        if (supplierPartyRole == null) {
            return "";
        }
        Party party = supplierPartyRole.getParty();
        String name = party != null ? (party.getAbbreviation() != null ? party.getAbbreviation() : party.getName()) : "";
        return name;
    }

    /**
     * 固定小数点点后两位(四舍五入)
     *
     * @param old
     * @return
     */
    private String twoDecimalPlacesRound(Double old) {
        double round = Math.round(old);
        DecimalFormat df = new DecimalFormat("#0.00");
        return df.format(round);
    }

    /**
     * 固定小数点点后两位
     *
     * @param old
     * @return
     */
    private String twoDecimalPlaces(Double old) {
        DecimalFormat df = new DecimalFormat("#0.00");
        return df.format(old);
    }

    /**
     * 从字符串中提取纯数字
     *
     * @param str
     * @return
     */
    public String getNumeric(String str) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 老系统扩展表数据
     *
     * @param extend
     * @param type
     * @return
     */
    private JSONObject extend(JSONObject extend, String type) {
        switch (type) {
            case "Accumulator": {//蓄电池
                JSONObject json = new JSONObject();
                json.put("K_M01010105001EDRLAH", extend.getDouble("capacity"));//额定容量[Ah])
                json.put("K_M01010105001EDDYV", extend.getDouble("voltage"));//额定电压[V])
                json.put("K_M01010105001GJBH", extend.getString("international"));//国际标号)
                json.put("K_M01010105001DZ", extend.getString("terminal"));//端子)
                json.put("K_M01010105001DCLX", extend.getString("type"));//电池类型)
                json.put("K_M01010105001CKH", extend.getString("reference"));//参考号)
                json.put("K_M01010105001LX", extend.getString("type"));//类型)
                json.put("K_M01010105001CCMM", extend.getString("sizes"));//尺寸[mm])
                json.put("K_M01010105001XL", extend.getString("series"));//系列)
                return json;
            }
            case "Tyre": {//轮胎
                JSONObject json = new JSONObject();
                json.put("K_M01010102001LTHW", extend.getString("figure"));//轮胎花纹)
                json.put("K_M01010102001ZZZS", extend.getString("loadIndex"));//载重指数)
                json.put("K_M01010102001SDDJ", extend.getString("speedClass"));//速度等级)
                json.put("K_M01010102001SFFB", extend.getBoolean("antiExplosion") ? "是" : "否");//是否防爆)
                json.put("K_M01010102001LTGG", extend.getString("specification"));//轮胎规格)
                return json;
            }
        }
        return new JSONObject();
    }

    /**
     * 获取销售价格
     *
     * @param product    商品信息
     * @param belongDept 门店
     * @return 销售价格
     */
    private JSONObject getRetailPrice(FnCustomerExpand fnCustomerExpand, Product product, Dept belongDept) {
        PartyRole platform = fnCommunalService.getPlatform(false, true, belongDept.getCompany().getParty().getCorporate().isWantInvoice(), false);
        //查询价格文件,获取销售价格
        JSONObject jsonObject = serviceToForeign.getXS51(
                MapUtil.mapper(
                        "uniqueIdentify", product.getId(),
                        "SPMC", product.getName(),
                        "MDID", belongDept.getId(),
                        "PLID", product.getClassify().getId(),
                        "SPID", product.getId(),
                        "PPID", product.getBrand().getId(),
                        "XSZZID", belongDept.getCompany().getId(),
                        "GSID", belongDept.getCompany().getId(),
                        "FNKHID", fnCustomerExpand.getUnitClientId(),
                        "CLFWDJID", ((CarServiceLevel) (SpringManager.getBean(CarServiceLevelService.class).findByCarConfigurationId(fnCustomerExpand.getJekunModelCode()))).getId(),
                        //"MDLXID", belongDept.getDeptType().getId(),
                        "FNVIPJBID", fnCustomerExpand.getCustomerLevelId(),
                        "FNVIPSFID", fnCustomerExpand.getUserRoleId(),
                        "CGZZID", platform.getId(),
                        "JLDW", product.getUom().getName(),
                        "JLDWID", product.getUom().getId(),
                        "JRS", fnCustomerExpand.getVendorCode(),
                        "SJHM", fnCustomerExpand.getMobile(),
                        "XSMD", belongDept.getId(),
                        "YYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getCode(),
                        "NYYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getId(),
                        "CPHM", fnCustomerExpand.getCarLicense(),
                        "SQID", SpringManager.getBean(StoreService.class).findBusinessCircleByDept(belongDept).getId(),
                        "XYGSID", belongDept.getCompany().getId(),
                        "KYS", 0
                ), true
        );
        return jsonObject;
    }

    /**
     * 获取询价价格
     * @param belongDept
     * @param serviceDept
     * @param product
     * @param fitting
     * @param fnCustomerExpand
     * @return
     */
    private JSONObject getAstrictPrice(Dept belongDept, Dept serviceDept, Product product, JSONObject fitting, FnCustomerExpand fnCustomerExpand) {
        JSONObject result = serviceToForeign.getXJ51(MapUtil.mapper(
                "uniqueIdentify", fitting.getJSONObject(""),
                "GSID", belongDept.getCompany().getId(),
                "XYGSID", belongDept.getCompany().getId(),
                "SYGSID", serviceDept.getCompany().getId(),
                "YYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getCode(),
                "NYYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getId(),
                "SPID", product.getId(),
                "PLID", product.getClassify().getId(),
                "JLDW", product.getUom().getName(),
                "FNKHID", fnCustomerExpand.getUnitClientId(),
                "FNVIPJBID", fnCustomerExpand.getCustomerLevelId(),
                "FNVIPSFID", fnCustomerExpand.getUserRoleId(),
                "JRS", fnCustomerExpand.getVendorCode(),
                "XSDJ", fitting.getString("priceUnit"),
                "XSXJ", fitting.getString("floorPrice"),
                "P001", fitting.getString("platformPriceCosInTax")
        ));
        return result;
    }

    /**
     * 获取供应商票点
     *
     * @param companyId  公司
     * @param SupplierId 供应商
     * @param brand      商品品牌
     * @param classify   商品品类
     * @return
     */
    public double getSupplierTicketPoint(String companyId, String SupplierId, String brand, String classify) {
        JSONObject param = new JSONObject();
        param.put("conditionStrategyId", "CG11");
        param.put("SYS_RQ", new Date());
        param.put("SUPPLIER_ID", SupplierId);
        param.put("COMPANY_ID", companyId);
        param.put("BRAND_ID", brand);
        if (Objects.nonNull(classify)) {
            param.put("CLASSIFY_ID", classify);
        }
        Object invoke = this.invoke("condition.execConditionStrategy", param);
        JSONObject result = new JSONObject(MapUtil.mapped(invoke));
        return result.getDoubleValue("P101");
    }

    /**
     * 加入购物车
     * sp = supplier(供应商)
     *
     * @param request
     * @return
     */
    public JSONObject addToShoppingCart(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject spProduct = requestJO.getJSONObject("condition");
        JSONObject conditionModel = requestJO.getJSONObject("conditionModel");
        JSONObject result = new JSONObject();

        //三头六臂商品加入购物车
        santouShopping(spProduct, conditionModel, result);

        return priceForward(spProduct, conditionModel, result);
    }

    //三头六臂商品加入购物车
    private JSONObject santouShopping(JSONObject spProduct, JSONObject conditionModel, JSONObject result){
        if (!"santou".equals(spProduct.getString("source"))) return result;
        String partName = spProduct.getString("name") + spProduct.getString("description");
        String notTaxUnitPrice = twoDecimalPlaces(spProduct.getDouble("salePrice"));//成本价
        if (StringUtils.isEmpty(spProduct.getString("priceSuggested"))) throw new RuntimeException("销售价格未加载完成，请稍等！");
        String priceSuggested = twoDecimalPlacesRound(spProduct.getDouble("priceSuggested"));//建议售价
        String notes = "成本价￥" + notTaxUnitPrice + "\n" + "建议售价:￥" + priceSuggested;//备注2
        String supplier = "三头六臂";//供应商
        Product product = productRepository.findOne(spProduct.getString("SPID"));
        spProduct.put("category",product.getCategory().getName());//配件名称
        spProduct.put("notTaxUnitPrice", notTaxUnitPrice);//成本价
        spProduct.put("taxUnitPrice", notTaxUnitPrice);//成本价
        spProduct.put("nakedPrice", notTaxUnitPrice);//裸价
        spProduct.put("fitting", MapUtil.mapped(product.getCategory()));//配件名称

        //购物车展示数据
        result.putAll(getResult(spProduct, "", partName, notes, supplier, 4));
        //获取部门
        Dept dept = SpringManager.getBean(DeptRepository.class).findOne(conditionModel.getJSONObject("serviceDept") == null ?
                conditionModel.getJSONObject("fixedLossDept").getString("id") : conditionModel.getJSONObject("serviceDept").getString("id"));
        //获取平台
        PartyRole platform = fnCommunalService.getPlatform(false, true, dept.getCompany().getParty().getCorporate().isWantInvoice(), false);
        //获取客户信息
        FnCustomerExpand fnCustomerExpand = getFnCustomerExpand(conditionModel.getJSONObject("fnCustomerExpandTemp").getString("carLicense"),
                SpringManager.getBean(AccessProviderRepository.class).findByCompany(dept.getCompany().getId()).getId());
        //获取销售51
        JSONObject retailPrice = getBean(SantouliubiService.class).getRetailPrice(fnCustomerExpand, product, dept);
        //获取价格规则
        JSONObject sale = this.invoke("scm.externalInquiry.newSystemPrice", MapUtil.mapper("P001", spProduct.getString("salePrice"), "PRODUCT_ID", product.getId(),
                "CLASSIFY_ID", product.getClassify().getId(), "BRAND_ID", product.getBrand().getId(), "SYS_RQ", new Date()));
        spProduct.put("sale", sale);

        //导入服务方案单明细
        result.putAll(getResultJson(conditionModel, spProduct, dept, platform, retailPrice, 4));
        result.put("product", product.getId());
        return result;
    }


    //价格前置商品加入购物车
    private JSONObject priceForward(JSONObject spProduct, JSONObject conditionModel, JSONObject result) {
        if (!result.isEmpty())return result;
        //初始化数据
        String oe = spProduct.getString("OE");//零件号
        String partName = partName(spProduct);//零件名称/商品名称
        String notTaxUnitPrice = twoDecimalPlaces(spProduct.getDouble("notTaxUnitPrice"));//成本价
        String priceSuggested = twoDecimalPlacesRound(spProduct.getDouble("priceSuggested"));//建议售价
        String notes = "成本价￥" + notTaxUnitPrice + "\n" + "建议售价:￥" + priceSuggested;//备注2
        String supplier = spProduct.getString("supplier");//供应商

        //购物车展示数据
        result.putAll(getResult(spProduct, oe, partName, notes, supplier, 1));
        //获取部门
        Dept dept = SpringManager.getBean(DeptRepository.class).findOne(conditionModel.getJSONObject("belongDept").getString("id"));
        //获取平台
        PartyRole platform = fnCommunalService.getPlatform(false, true, dept.getCompany().getParty().getCorporate().isWantInvoice(), false);
        //导入服务方案单明细
        result.putAll(getResultJson(conditionModel, spProduct, dept, platform, spProduct.getJSONObject("resultJsonReback"), 1));
        return result;
    }

    /**
     * 拼接购物车数据
     *
     * @param spProduct 供应商商品信息
     * @param oe        oe号
     * @param partName  conditionModel.getJSONObject("")
     * @param notes     备注1
     * @param supplier  供应商名称
     * @param num       渠道类型 1：价格前置标记 2：新平台询价 3：询价执行表 4：三头六臂 5：巴图鲁 6：外采
     * @return
     */
    private JSONObject getResult(JSONObject spProduct, String oe, String partName, String notes, String supplier, Integer num) {
        JSONObject result = new JSONObject();
        result.put("partName", partName);//零件名称/商品名称
        result.put("name", partName);//名称
        result.put("partCode", spProduct.getString("id"));//零件编码/商品编码
        result.put("oldPartCode", spProduct.getString("id"));//零件号
        result.put("parts", Arrays.asList(MapUtil.mapper("PJMC", StringUtils.isEmpty(spProduct.getString("category")) ? "---" : spProduct.getString("category"))));//配件名称
        result.put("orderQuantity", spProduct.getString("orderQuantity"));//订单数
        result.put("notes", supplier + "发货");//备注1
        result.put("positionConfirma", notes);//备注2
        result.put("innerBusinessKey", spProduct.getString("id"));//标记
        result.put("priceForward", num);//渠道类型
        result.put("spProduct", spProduct.getJSONObject("spProduct"));//商品
        result.put("stateName", "新增");
        return result;
    }


    /**
     * 拼接零件名称/商品名称
     *
     * @param spProduct
     * @return
     */
    private String partName(JSONObject spProduct) {
        if (spProduct.getIntValue("num") == 6) {
            return spProduct.getString("productName");
        }
        String spBrand = getBrandName(spProduct.getJSONObject("spBrand"));//品牌
        switch (spProduct.getString("standardType")) {
            case "Accumulator": {//蓄电池
                String category = StringUtils.isEmpty(spProduct.getString("category")) ? "蓄电池" : spProduct.getString("category");//标准名称
                String international = spProduct.getString("international");//国际标号
                String reference = spProduct.getString("reference");//参考号
                return spBrand + category + international + reference;
            }
            case "Tyre": {//轮胎
                String category = StringUtils.isEmpty(spProduct.getString("category")) ? "轮胎" : spProduct.getString("category");//标准名称
                String specification = spProduct.getString("specification");//规格
                String figure = spProduct.getString("figure");//花纹
                String antiExplosion = "是".equals(spProduct.getString("antiExplosion")) ? "防爆" : "";
                String loadIndex = spProduct.getString("loadIndex");//载重等级
                String speedClass = spProduct.getString("speedClass");//速度等级
                String name = spBrand + category + specification + "(花纹" + figure + ")" + antiExplosion + "/" + loadIndex + speedClass;
                return name.toUpperCase();
            }
            case "Oily": {//机油
                String catena = spProduct.getString("catena");//系列
                String type = spProduct.getString("type");//机油类型
                String apiClass = spProduct.getString("apiClass");//API等级
                String viscosityClass = spProduct.getString("viscosityClass");//粘度等级
                String capacity = spProduct.getString("capacity");//容量
                return spBrand + catena + type + "(" + apiClass + ")" + viscosityClass + "/" + capacity + "L";
            }
        }
        String name = StringUtils.isEmpty(spProduct.getString("category")) ? spProduct.getString("name") : spProduct.getString("category");//名称
        String oe = spProduct.getString("pn");//零件号
        if (StringUtils.isEmpty(oe)) {
            return spBrand + name;
        }
        return spBrand + name + oe;
    }

    //获取品牌名称
    private String getBrandName(JSONObject brand){
        if ("名牌".equals(brand.getString("name")) || "003543".equals(brand.getString("id"))){
            return "MP";
        }
        if ("拆车".equals(brand.getString("name")) || "005507".equals(brand.getString("id"))){
            return "CC";
        }
        if ("下线".equals(brand.getString("name")) || "005508".equals(brand.getString("id"))
                || "原厂同质下线".equals(brand.getString("name")) || "015403".equals(brand.getString("id"))){
            return "XX";
        }
        return brand.getString("name");//品牌
    }

    /**
     * 拼接服务方案单明细
     *
     * @param conditionModel   前端数据
     * @param spProduct        供应商商品
     * @param belongDept       门店
     * @param platform         平台
     * @param resultJsonReback 销售51
     * @param num 1：价格前置标记 2：新平台询价 3：询价执行表 4：三头六臂 5：巴图鲁 6：外采
     * @return
     */
    private JSONObject getResultJson(JSONObject conditionModel, JSONObject spProduct, Dept belongDept, PartyRole platform, JSONObject resultJsonReback, Integer num) {
        JSONObject resultJson = new JSONObject();
        JSONObject fitting = spProduct.getJSONObject("fitting");
        resultJson.put("haveOffice", "暂无报价");
        //库区额外信息
        resultJson.put("company", belongDept.getCompany());
        resultJson.put("platform", platform);
        //商品
        if (Objects.nonNull(fitting)) {
            resultJson.put("category", fitting.size() == 0 ? null : fitting);
            resultJson.put("fitting", fitting.size() == 0 ? null : fitting);
        }

        price(spProduct, belongDept, resultJsonReback, resultJson);

        resultJson = (JSONObject) serviceToForeign.priceRoundUp(resultJson, 2);
        //前端要求需要返回的
        resultJson.put("inquirySelectFlag", 1);
        resultJson.put("node", conditionModel.getJSONObject("node"));
        resultJson.put("assistType", SpringManager.getBean(BusinessAttributeValueRepository.class).findOne("ServicePlanItem.assistType.normal"));
        //单独返回默认销售数量
        resultJson.put("saleQty", 1);
        //带安标记
        boolean productRule = spProduct.containsKey("productRule") ? spProduct.getBoolean("productRule") : false;
        resultJson.put("productRule", productRule);
        try {
            if (conditionModel.getJSONObject("node") != null) {
                resultJson.put("higherLevelCode", conditionModel.getJSONObject("node").getJSONObject("product").getString("id"));
            }
        } catch (Exception e) {
            throw new RuntimeException("miss:nodeDie");
        }
        Location location;
        try {
            location = SpringManager.getBean(LocationService.class).findLocationByDept(belongDept, productRule);
            if (productRule) {
                if (location == null) throw new RuntimeException("门店没有设置带安虚拟库，门店名称：" + belongDept.getName());
            } else {
                if (location == null) throw new RuntimeException("未找到门店对应的仓库" + belongDept.getName());
            }
            resultJson.put("location", location);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        resultJson.put("platform", platform);//平台
        resultJson.put("priceForward", num);//渠道
        if (StringUtils.isNotEmpty(spProduct.getString("ERPProduct"))){
            resultJson.put("product", spProduct.getString("ERPProduct"));//平台商品id
        }
        //询价
        enquiry(spProduct, num, resultJson);//num：渠道类型 1==价格前置标记，2==新平台询价 ， 3==询价执行表, 4==三头六臂
        //供应商商城
        priceForward(spProduct, num, resultJson);
        //三头六臂
        santou(spProduct, num, resultJson);
        //巴图鲁
        baturu(spProduct, num, resultJson);
        //外采
        lightningQuotationFindPrice(spProduct, num, resultJson);
        return resultJson;
    }


    private void lightningQuotationFindPrice(JSONObject spProduct, Integer num, JSONObject resultJson){
        if (num != 6) return;
        resultJson.put("supplier", partyRoleRepository.findByName(spProduct.getString("supplier")));
        resultJson.put("inquiryGooodsState", spProduct.getString("inquiryGooodsState"));//货源状态
        resultJson.put("uniqueValue", spProduct.getString("uniqueValue"));//唯一值  报价ID
        resultJson.put("oldInquiryNumber", spProduct.getString("enquiryId"));//询价单号
    }

    /**
     * 巴图鲁
     * @param spProduct
     * @param num 渠道类型 1==价格前置标记，2==新平台询价 ， 3==询价执行表, 4==三头六臂, 5==巴图鲁
     * @param resultJson
     */
    private void baturu(JSONObject spProduct, Integer num, JSONObject resultJson){
        if (num != 5) return;
        String placeOfDispatch = spProduct.getJSONObject("quoteResult").getString("placeOfDispatch");//货源状态
        resultJson.put("inquiryGooodsState", "0".equals(placeOfDispatch) ? "3" : "2");//货源状态
        resultJson.put("purchaseRemarks", "下单后" + placeOfDispatch + "天送达广州中转站");//货源状态
        resultJson.put("expectedArrivalTimeTemp", placeOfDispatch);//货源状态
        resultJson.put("uniqueValue", spProduct.getString("id"));//唯一值用来记录巴图鲁平台的商品id
        String baturuSupplierId = spProduct.getJSONObject("spProduct").getJSONObject("supplier").getString("id");
        PartyRole baturu = getBean(PartyRoleRepository.class).findOne(baturuSupplierId);
        resultJson.put("supplier", baturu);
        if (spProduct.getString("enquiry") != null) {
            resultJson.put("oldInquiryNumber", spProduct.getString("enquiry"));//询价单号  新平台询价单号
        }
    }

    /**
     * 三头六臂
     * @param spProduct
     * @param num 渠道类型 1==价格前置标记，2==新平台询价 ， 3==询价执行表, 4==三头六臂
     * @param resultJson
     */
    private void santou(JSONObject spProduct, Integer num, JSONObject resultJson){
        if (num != 4) return;
        resultJson.put("inquiryGooodsState", 3);//货源状态
        resultJson.put("uniqueValue", spProduct.getString("productNumber"));//唯一值用来记录三头六臂平台的商品id
        SantouChannel santouChannel = getBean(SantouChannelRepository.class).findByChannelNumber(spProduct.getString("merchantsId"));
        resultJson.put("supplier", santouChannel.getSupplier());
    }

    //价格前置商品
    private void priceForward(JSONObject spProduct, Integer num, JSONObject resultJson) {
        if (num != 1) return;
        resultJson.put("inquiryGooodsState", 3);//货源状态
        resultJson.put("uniqueValue", spProduct.getString("id"));//唯一值用来记录供应商平台的商品id
        resultJson.put("supplier", partyRoleRepository.findOne(spProduct.getJSONObject("spProduct").getJSONObject("supplier").getString("id")));//供应商
    }

    //询报价商品
    private void enquiry(JSONObject spProduct, Integer num, JSONObject resultJson) {
        if (num != 2) return;
        String placeOfDispatch = spProduct.getJSONObject("quoteResult").getString("placeOfDispatch");//货源状态
        resultJson.put("inquiryGooodsState", "0".equals(placeOfDispatch) ? "3" : "2");//货源状态
        resultJson.put("purchaseRemarks", "下单后" + placeOfDispatch + "天送达广州中转站");//货源状态
        resultJson.put("expectedArrivalTimeTemp", placeOfDispatch);//货源状态
        resultJson.put("supplier", partyRoleRepository.findOne(spProduct.getJSONObject("spProduct").getJSONObject("supplier").getString("id")));//供应商
        if (spProduct.getString("uniqueValue") == null) {
            resultJson.put("uniqueValue", spProduct.getString("auoteResult") + spProduct.getString("id"));//唯一值  报价ID
        }
        resultJson.put("oldInquiryNumber", StringUtils.isNotEmpty(spProduct.getString("enquiry")) ? spProduct.getString("enquiry") : spProduct.getString("enquiryId"));//询价单号  新平台询价单号

    }

    /**
     * 设置服务方案明细价格
     *
     * @param spProduct        供应商商品信息
     * @param belongDept       门店
     * @param resultJsonReback 销售51
     * @param resultJson       服务方案明细
     */
    private void price(JSONObject spProduct, Dept belongDept, JSONObject resultJsonReback, JSONObject resultJson) {
        //价格
        if ((!resultJsonReback.isEmpty()) && resultJsonReback.getDouble("priceUnit") != 0.0) {
            resultJson.put("primaryPriceUnit", resultJsonReback.getDouble("primaryPriceUnit"));//零售价
            resultJson.put("primaryPriceUnitShow", resultJsonReback.getDouble("primaryPriceUnit"));//原销售单价展示
            resultJson.put("priceUnit", resultJsonReback.getDouble("priceUnit"));//销售单价
            resultJson.put("priceApprovalAmt", resultJsonReback.getDouble("priceUnit"));//通过价格审核的价格
            resultJson.put("priceSource", resultJsonReback.getString("priceSource"));//价格来源日志编码
            resultJson.put("pftPriceUnit", resultJsonReback.getDouble("pftPriceUnit"));//优惠单价
            resultJson.put("priceFlag", resultJsonReback.getDouble("priceUnit") > 0);//是否取到价格
            resultJson.put("managementFeeRate", resultJsonReback.getDouble("managementFeeRate"));//管理费率
            resultJson.put("floorPrice", resultJsonReback.getDouble("floorPrice"));//最低限价
            resultJson.put("clerkPriceLimit", resultJsonReback.getDouble("clerkPriceLimit"));//店员限价
            resultJson.put("shopOwnerPriceLimit", resultJsonReback.getDouble("shopOwnerPriceLimit"));//店长限价
            resultJson.put("csoPriceLimit", resultJsonReback.getDouble("csoPriceLimit"));//销售总监限价
            resultJson.put("basePrice", resultJsonReback.getDouble("basePrice"));//销售基准价
            resultJson.put("discountRate", Objects.isNull(resultJsonReback.getDouble("discountRate")) ? 0 : resultJsonReback.getDouble("discountRate"));//折扣率
            resultJson.put("priceCostUnitInTax", spProduct.getDouble("notTaxUnitPrice"));//含税成本单价
            resultJson.put("priceCostUnitExTax", spProduct.getDouble("nakedPrice"));//裸价
            resultJson.put("platformPriceCosInTax", spProduct.getDouble("notTaxUnitPrice")); //平台成本价
            resultJson.put("referTax", spProduct.getDouble("notTaxUnitPrice")); //参考成本
            double fee = SpringManager.getBean(FeeRateService.class).getSupplyChainManagementFee(belongDept.getCompany().getId(), spProduct.getString("classify"), "");
            resultJson.put("supplyChainManagement", Arith.round(resultJsonReback.getDouble("supplyChainManagement") * fee, 2)); //供应链管理费用
            resultJson.put("inquiryPriceUnit", resultJsonReback.getDoubleValue("inquiryPriceUnit"));//询价销售单价
            resultJson.put("inquiryPriceLimit", resultJsonReback.getDoubleValue("inquiryPriceLimit"));//询价销售限价
            resultJson.put("vipDiscountType", resultJsonReback.getDoubleValue("vipDiscountRate") < 1 ? "vipDiscountRate" : resultJsonReback.getDoubleValue("vipDiscountPrice") > 0 ? "vipDiscountPrice" : null);//会员折扣类型
        } else {
            if (spProduct.isEmpty()) return;

            resultJson.put("primaryPriceUnit", spProduct.getDouble("priceSuggested"));//零售价
            resultJson.put("primaryPriceUnitShow", spProduct.getDouble("priceSuggested"));//原销售单价展示
            resultJson.put("priceUnit", spProduct.getDouble("priceSuggested"));//销售单价
            resultJson.put("salesAmount", spProduct.getDouble("priceSuggested"));//销售金额
            resultJson.put("pftPriceUnit", spProduct.getDouble("priceSuggested"));//优惠单价
            resultJson.put("priceFlag", true);//是否取到价格
            resultJson.put("floorPrice", spProduct.getJSONObject("sale").getDouble("XSXJ"));//最低限价
            resultJson.put("basePrice", spProduct.getJSONObject("sale").getDouble("XSXJ"));//销售基准价
            resultJson.put("priceCostUnitInTax", spProduct.getDouble("notTaxUnitPrice"));//含税成本单价
            resultJson.put("priceCostUnitExTax", spProduct.getDouble("nakedPrice"));//裸价
            resultJson.put("platformPriceCosInTax", spProduct.getDouble("notTaxUnitPrice")); //平台成本价
            resultJson.put("referTax", spProduct.getDouble("notTaxUnitPrice")); //参考成本
        }
    }

    /**
     * 导入服务方案前再次设置价格
     */
    public JSONObject onceAgainPrice(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        Dept belongDept = new Dept();
        Dept serviceDept = new Dept();
        if (Objects.nonNull(requestJO.getJSONObject("serviceDept"))) {
            belongDept = deptRepository.findOne(requestJO.getJSONObject("belongDept").getString("id"));//方案门店
            serviceDept = deptRepository.findOne(requestJO.getJSONObject("serviceDept").getString("id"));//服务门店
        } else {
            if (StringUtils.isNotEmpty(requestJO.getString("fixedLossDeptId"))){
                belongDept = deptRepository.findOne(requestJO.getString("fixedLossDeptId"));
                serviceDept = deptRepository.findOne(requestJO.getString("fixedLossDeptId"));
            }else {
                belongDept = deptRepository.findOne(requestJO.getJSONObject("dept").getString("id"));
                serviceDept = deptRepository.findOne(requestJO.getJSONObject("dept").getString("id"));
            }

        }
        boolean sign = "定损报价单1".equals(requestJO.getString("orderTypeTemp")) || "定损报价单".equals(requestJO.getString("orderTypeTemp"));
        //客户扩展信息
        FnCustomerExpand fnCustomerExpand = getCustomerExpand(requestJO, sign);

        JSONObject servicePlanItem = requestJO.getJSONObject("servicePlanItem");
        Product product = (Product) servicePlanItem.get("product");
        //获取询价51
        JSONObject resultJsonReback = getAstrictPrice(belongDept, serviceDept, product, servicePlanItem, fnCustomerExpand);

        //设置限价和供应链管理费用
        servicePlanItem.put("clerkPriceLimit", resultJsonReback.getDouble("clerkPriceLimit"));//店员限价
        servicePlanItem.put("shopOwnerPriceLimit", resultJsonReback.getDouble("shopOwnerPriceLimit"));//店长限价
        //servicePlanItem.put("saleQty", "");//店长限价
        servicePlanItem.put("csoPriceLimit", resultJsonReback.getDouble("csoPriceLimit"));//销售总监限价
        servicePlanItem.put("managementFeeRate", resultJsonReback.getDouble("managementFeeRate"));//管理费率
        servicePlanItem.put("basePrice", resultJsonReback.getDouble("basePrice"));//销售基准价
        servicePlanItem.put("priceApprovalAmt", resultJsonReback.getDouble("priceUnit"));//通过价格审核的价格
        servicePlanItem.put("pftPriceUnit", resultJsonReback.getDouble("priceUnit"));//优惠单价
        servicePlanItem.put("salesAmount", resultJsonReback.getDouble("priceUnit"));//最终销售金额
        servicePlanItem.put("discountRate", resultJsonReback.getDouble("discountRate").isNaN() ? 0 : resultJsonReback.getDouble("discountRate"));//折扣率
        double fee = SpringManager.getBean(FeeRateService.class).getSupplyChainManagementFee(belongDept.getCompany().getId(), product.getClassify().getId(), "");
        servicePlanItem.put("supplyChainManagement", Arith.round(resultJsonReback.getDouble("supplyChainManagement") * fee, 2)); //供应链管理费用
        if (servicePlanItem.getString("priceForward") != null && servicePlanItem.getString("priceForward").equals("1")) {
            servicePlanItem.put("salesAmount", servicePlanItem.getDouble("primaryPriceUnitShow") * servicePlanItem.getInteger("orderQuantity"));
        }
        servicePlanItem.put("mapAddress", new ArrayList<>()); //供应链管理费用
        if (sign) {
            servicePlanItem.put("evaluationType", getBean(BusinessAttributeValueRepository.class).findOne("LossQuotationItem.evaluationType.B"));
            servicePlanItem.put("salePrice", resultJsonReback.getDouble("priceUnit"));
            servicePlanItem.put("salesAmount", resultJsonReback.getDouble("priceUnit"));
            servicePlanItem.put("minimumPrice", resultJsonReback.getDouble("floorPrice"));
            servicePlanItem.put("serveType", "000609".equals(servicePlanItem.getJSONObject("fitting").getString("id")) ? getBean(ServeTypeRepository.class).findOne("021") : getBean(ServeTypeRepository.class).findOne("004"));
        }
        return servicePlanItem;
    }

    //获取客户扩展信息
    private FnCustomerExpand getCustomerExpand(JSONObject requestJO, boolean sign){
        String fnCustomerExpand = "";
        if (sign){
            fnCustomerExpand = "customerExpand";
        }else {
            fnCustomerExpand = "fnCustomerExpand";
        }
        if (Objects.isNull(requestJO.getJSONObject(fnCustomerExpand))){
            return JSON.parseObject(requestJO.getJSONObject("fnCustomerExpandTemp").toJSONString(), FnCustomerExpand.class);
        }
        return getBean(FnCustomerExpandRepository.class).findOne(requestJO.getJSONObject(fnCustomerExpand).getString("id"));
    }


    /**
     * 根据门店和Vin码查询闪电报价
     *
     * @param request
     * @return
     */
    public Map queryPriceForwardOE(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        String deptId = "";
        //获取门店
        if (Objects.isNull(requestJO.getJSONObject("belongDept"))) {
            deptId = requestJO.getJSONObject("fixedLossDept").getString("id");
        } else {
            deptId = requestJO.getJSONObject("belongDept").getString("id");
        }
        String VIN = requestJO.getJSONObject("customerCar").getString("vin");
        platform = requestJO.getString("platform");
        spProductMap = new HashMap<>();

        Map param = MapUtil.mapper("dept", deptId, "VIN", VIN);//匹配商品参数
        //获取供应商平台报价商品
        JSONObject json = JSON.parseObject(invoke("sp.matching.lightningOffer", param));
        JSONArray body = json.getJSONArray("body");//供应商返回的数据
        Map<String,List<Object>> map = body.stream().collect(Collectors.groupingBy(item -> ((JSONObject)item).getJSONObject("product").getString("standardType")));
        Dept dept = deptRepository.findOne(deptId);
        FnCustomerExpand fnCustomerExpand = JSON.parseObject(requestJO.getString("fnCustomerExpandTemp"), FnCustomerExpand.class);
        JSONObject content = new JSONObject();
        JSONArray results = new JSONArray();
        map.forEach((k,v)->{
            JSONArray array =JSONArray.parseArray(JSON.toJSONString(v));
            Map result = getResult(array, dept, fnCustomerExpand);//按标准名称分类商品获取销售价格
            results.addAll((List)result.get("content"));//商品列表
        });
        content.put("item", results);
        return MapUtil.mapper("item", content);
    }

    /**
     * 闪电报价商品导入服务方案
     *
     * @param request
     * @return
     */
    public JSONArray inputServicePlanItem(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONArray data = requestJO.getJSONArray("data");
        JSONObject model = request.getJO().getJSONObject("model");
        String id = "";
        boolean sign = Objects.nonNull(model.getJSONObject("fixedLossDept"));//定损标记
        if (sign) {
            id = model.getJSONObject("fixedLossDept").getString("id");
        } else {
            id = model.getJSONObject("belongDept").getString("id");
        }
        //获取方案门店
        Dept belongDept = deptRepository.findOne(id);
        //获取平台
        PartyRole platform = fnCommunalService.getPlatform(false, true, belongDept.getCompany().getParty().getCorporate().isWantInvoice(), false);
        requestJO.getString("model");
        //获取巴图鲁供应商信息
        JSONObject JS = JSONObject.parseObject(invoke("sp.BusinessParamService.findAllByQueryKey", MapUtil.mapper("queryKey", "baturuSupplierNumber")));
        String[] split = JS.getJSONObject("body").getString("value").replace("[", "").replace("]", "").split(",");
        List<String> supplierIds = Arrays.asList(split);

        JSONArray results = new JSONArray();
        //导入服务方案单和定损报价单明细数据
        for (Object o : data) {
            JSONObject spProduct = (JSONObject) o;
            String partName = partName(spProduct);//零件名称/商品名称
            Integer num = spProduct.getInteger("num");
            //若为巴图鲁商品则设置为巴图鲁的渠道码
            if (spProduct.getJSONObject("spProduct").containsKey("supplier") &&
                    supplierIds.contains(spProduct.getJSONObject("spProduct").getJSONObject("supplier").getString("id"))){
                num = 5;
            }
            JSONObject result = getResult(spProduct, spProduct.getString("OE"), partName, "", spProduct.getString("supplier"), num);//拼接商品数据
            result.putAll(getResultJson(new JSONObject(), spProduct, belongDept, platform, new JSONObject(), num));//拼接服务方案单明细
            result.put("partCode", spProduct.getJSONObject("spProduct").getString("OE"));//零件编码/商品编码
            result.put("uniqueValue", spProduct.getString("uniqueValue"));//唯一值
            if (StringUtils.isEmpty(result.getString("oldInquiryNumber"))) {
                result.put("oldInquiryNumber", spProduct.getString("enquiryId"));
            }
            result.put("quoteResultId",spProduct.getString("quoteResultId"));
            //询价单来源配件判断是否需要生成
            if (Objects.isNull(spProduct.getJSONObject("fitting")) || "013951".equals(spProduct.getJSONObject("fitting").getString("id"))) {
                Category category = categoryRepository.findByName(spProduct.getString("productName"));
                while (Objects.isNull(category)) {
                    JSONObject message = getBean(PiManager.class).synErp("scmGysxjdService.matchPJMC", MapUtil.mapper("PJMC", spProduct.getString("productName")));
                    JSONObject fitting = JSON.parseObject(message.getString("obj"));
                    try {
                        category = categoryRepository.findOne(fitting.getString("PJMCID"));
                    } catch (Exception exception) {
                        System.out.println("老系统生成标准配件中。。。");
                    }
                }
                JSONObject categoryJSON = new JSONObject();
                categoryJSON.put("id", category.getId());
                categoryJSON.put("name", category.getName());
                result.put("category", categoryJSON);
                result.put("fitting", categoryJSON);
            }
            if (StringUtils.isNotEmpty(spProduct.getString("ERPProductId"))){
                result.put("product", spProduct.getString("ERPProductId"));
            }
            if (sign) {
                result.put("evaluationType", getBean(BusinessAttributeValueRepository.class).findOne("LossQuotationItem.evaluationType.B"));
                result.put("salePrice", result.getDouble("priceUnit"));
                result.put("minimumPrice", result.getDouble("floorPrice"));
                result.put("serveType", "000609".equals(result.getJSONObject("fitting").getString("id")) ? getBean(ServeTypeRepository.class).findOne("021") : getBean(ServeTypeRepository.class).findOne("004"));
            }
            //生成商品
            SpringManager.getBean(ProductService.class).priceForward(results, result, model);
        }

        return results;
    }

    /**
     * 闪电报价导入服务方案单
     *
     * @param request
     * @return
     */
    public JSONObject oneInputServicePlanItem(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONArray array = new JSONArray(Arrays.asList(requestJO.getJSONObject("data")));
        requestJO.put("data", array);
        request.setData(requestJO);
        JSONArray results = inputServicePlanItem(request);
        if (results.isEmpty()) throw new RuntimeException("未生成系统商品，请联系ERP对接人！");
        return (JSONObject) results.stream().findFirst().get();
    }

    /**
     * 合并新老系统询价结果
     *
     * @param request
     * @return
     */
    public Map mergeResult(SimpleRequest request) {
        //新平台询价结果
        Map priceForward = queryPriceForwardOE(request);
        JSONArray newEnquiryItem = ((JSONObject)priceForward.get("item")).getJSONArray("item");
        //老系统询价结果
        JSONObject param = request.getJO();
        JSONObject response = JSONObject.parseObject(JSONObject.toJSONString(invoke("commodityInquiry.order.getInquiryPool", param)));
        JSONArray oldEnquiryItem = response.getJSONArray("item");
        //外采
        JSONArray externalInquiry = externalInquiry(param);
        //合并新老系统询价结果
        String deptId = StringUtils.isNotEmpty(param.getString("saleDept")) ? param.getJSONObject("saleDept").getString("id"):param.getString("fixedLossDeptId");
        JSONArray results = change(newEnquiryItem, oldEnquiryItem, deptId);
        results.addAll(externalInquiry);
        Map map = new HashMap();
        map.put("results",results);
        map.put("enquiryId","");
        map.put("sign",true);
        return map;
    }

    //外采
    private JSONArray externalInquiry(JSONObject param){
        String deptId = "";
        //获取门店
        if (Objects.isNull(param.getJSONObject("belongDept"))) {
            deptId = param.getJSONObject("fixedLossDept").getString("id");
        } else {
            deptId = param.getJSONObject("belongDept").getString("id");
        }
        List item = invoke("scm.externalInquiryService.lightningQuotationFindPrice",
                MapUtil.mapper("externalInquiry.sourceBusinessKey", param.getString("sourceBusinessKey"),
                        "externalInquiry.customerExpand.vin", param.getJSONObject("customerCar").getString("vin"),
                        "externalInquiry.dept.id", deptId));
        JSONArray enquiryArray = new JSONArray(item);
        JSONArray results = new JSONArray();
        //前端分组
        Map<String, List<Object>> categoryId = enquiryArray.stream().collect(Collectors.groupingBy(requireItem -> {
            return ((JSONObject) requireItem).getString("categoryName");
        }));
        categoryId.forEach((k, v) -> {
            JSONObject result = new JSONObject();
            result.put("categoryId", k);
            result.put("item", v);
            v.forEach(o -> manageData((JSONObject) o));
            JSONObject enquiryItem = (JSONObject) v.get(0);
            result.put("categoryName", enquiryItem.getString("categoryName"));
            results.add(result);
        });
        return results;
    }

    /** 处理外采询价的数据*/
    private JSONObject manageData(JSONObject enquiryItem){
        enquiryItem.put("num", 6);
        enquiryItem.put("ssign", "01");
        enquiryItem.put("sale", new JSONObject(MapUtil.mapper("XSDJ", enquiryItem.getDouble("XSDJ"),"XSXJ", enquiryItem.getDouble("taxUnitPrice"))));
        enquiryItem.put("ERPProductId", enquiryItem.getJSONObject("spProduct").getString("id"));
        return enquiryItem;
    }

    //合并询价结果
    private JSONArray change(JSONArray newEnquiryItem, JSONArray oldEnquiryItem, String deptId) {
        JSONArray enquiryArray = new JSONArray();
        JSONArray results = new JSONArray();
        //遍历配件分组结果集
        if (newEnquiryItem != null){
            newEnquiryItem.forEach(o -> {
                JSONObject groupItem = (JSONObject) o;
                groupItem.put("ssign", "01");
                groupItem.put("num", 2);
                enquiryArray.add(groupItem);
            });
        }
        if (oldEnquiryItem != null) {
            oldEnquiryItem.forEach(o -> {
                JSONObject groupItem = (JSONObject) o;
                JSONArray item = groupItem.getJSONArray("item");
                item.forEach(j -> ((JSONObject) j).put("ssign", "00"));
                enquiryArray.addAll(item);
            });
        }
        //遍历配件明细
        enquiryArray.forEach(o -> {
            JSONObject enquiryItem = (JSONObject) o;
            //替换配件明细字段
            replace(enquiryItem, deptId);
        });
        //前端分组
        Map<String, List<Object>> categoryId = enquiryArray.stream().collect(Collectors.groupingBy(requireItem -> {
            return ((JSONObject) requireItem).getString("categoryName");
        }));
        categoryId.forEach((k, v) -> {
            JSONObject result = new JSONObject();
            result.put("categoryId", k);
            result.put("item", v);
            JSONObject enquiryItem = (JSONObject) v.get(0);
            result.put("categoryName", enquiryItem.getString("categoryName"));
            results.add(result);
        });
        return results;
    }

    //替换配件明细字段
    // enquiryItem 询价结果明细
    private JSONObject replace(JSONObject enquiryItem, String deptId) {
        enquiryItem.put("pn", StringUtils.isNotEmpty(enquiryItem.getString("pn")) ? enquiryItem.getString("pn") : null);//零件号
        enquiryItem.put("qualityName", StringUtils.isNotEmpty(enquiryItem.getString("spProduct")) ? enquiryItem.getJSONObject("spProduct").getString("qualityName") : enquiryItem.getString("PZMC"));//品质名称
        enquiryItem.put("Brand", StringUtils.isNotEmpty(enquiryItem.getString("spBrand")) ? enquiryItem.getJSONObject("spBrand").getString("name") : enquiryItem.getString("PPMC"));//品牌
        enquiryItem.put("notTaxUnitPrice", StringUtils.isNotEmpty(enquiryItem.getString("notTaxUnitPrice")) ? enquiryItem.getDouble("notTaxUnitPrice") : enquiryItem.getDouble("CGDJ"));//成本价
        enquiryItem.put("XSDJ", twoDecimalPlacesRound(StringUtils.isNotEmpty(enquiryItem.getString("priceSuggested")) ? enquiryItem.getDouble("priceSuggested") : enquiryItem.getDouble("XSDJ")));//零售价
        enquiryItem.put("supplier", enquiryItem.getString("supplier"));//供应商代码
        enquiryItem.put("productName", StringUtils.isNotEmpty(enquiryItem.getString("productName")) ? enquiryItem.getString("productName") : enquiryItem.getString("PJMC"));//标准名称
        enquiryItem.put("address", StringUtils.isNotEmpty(enquiryItem.getString("address")) ? enquiryItem.getString("address") : enquiryItem.getString("deliveryPlace"));//发货地
        enquiryItem.put("state", StringUtils.isNotEmpty(enquiryItem.getString("state")) ? enquiryItem.getString("state") : enquiryItem.getString("HYMC"));//货源
        enquiryItem.put("note", StringUtils.isNotEmpty(enquiryItem.getString("note")) ? enquiryItem.getString("note") : enquiryItem.getString("GYSBZ"));//供应商备注
        enquiryItem.put("png", StringUtils.isNotEmpty(enquiryItem.getString("png")) ? enquiryItem.getString("png") : enquiryItem.getString("THIRD_SUPPLIER_PICTURES"));//图片
        enquiryItem.put("SPID", StringUtils.isNotEmpty(enquiryItem.getString("pn")) ? enquiryItem.getString("pn") : enquiryItem.getString("SPID"));//商品id
        enquiryItem.put("categoryId", StringUtils.isNotEmpty(enquiryItem.getString("fitting")) ? enquiryItem.getJSONObject("fitting").getString("id") : enquiryItem.getString("PJMCID"));
        enquiryItem.put("categoryName", StringUtils.isNotEmpty(enquiryItem.getString("fitting")) ? enquiryItem.getString("category") : enquiryItem.getString("PJMC"));//配件名称
        enquiryItem.put("png", StringUtils.isNotEmpty(enquiryItem.getString("THIRD_SUPPLIER_PICTURES")) ? enquiryItem.getString("THIRD_SUPPLIER_PICTURES") : enquiryItem.getString("png"));
        String uniqueValue = "";
        if (StringUtils.isNotEmpty(enquiryItem.getString("quoteResultId")) && StringUtils.isNotEmpty(enquiryItem.getString("spProduct"))) {
            uniqueValue = enquiryItem.getString("quoteResultId") + "/" + enquiryItem.getJSONObject("spProduct").getString("id");
        }
        enquiryItem.put("uniqueValue", StringUtils.isNotEmpty(enquiryItem.getString("WYZ")) ? enquiryItem.getString("WYZ") : uniqueValue);
        enquiryItem.put("WYZ", StringUtils.isNotEmpty(enquiryItem.getString("WYZ")) ? enquiryItem.getString("WYZ") : uniqueValue);
        if ("01".equals(enquiryItem.getString("ssign"))) {
            enquiryItem.put("MDID", deptId);
            enquiryItem.put("logisticsMode", MapUtil.mapper("id", "logisticsMode", "name", "商家配送"));
            enquiryItem.put("SPMC", enquiryItem.getJSONObject("spProduct").getString("name"));
            if (Objects.nonNull(enquiryItem.getJSONObject("spBrand").getJSONObject("subQuality"))){
                enquiryItem.put("XFPZJC", enquiryItem.getJSONObject("spBrand").getJSONObject("subQuality").getString("XFPZJC"));
                enquiryItem.put("XFPZDY", enquiryItem.getJSONObject("spBrand").getJSONObject("subQuality").getString("XFPZDY"));
            }
            enquiryItem.put("inquiryGooodsState", "0".equals(enquiryItem.getJSONObject("quoteResult").getString("placeOfDispatch")) ? "3" : "2");
            enquiryItem.put("purchaseInformation",enquiryItem.getJSONObject("quoteResult").getString("purchaseInformation"));
            enquiryItem.put("ZBQ",enquiryItem.getJSONObject("quoteResult").getString("ZBQ"));
        }
        return enquiryItem;
    }

    /**
     * 询价结果详情信息展示
     * @param request
     * @return
     */
    public Map enquiryParticulars(SimpleRequest request) {
        JSONObject requestJO = request.getJO().getJSONObject("node");
        String deptId = requestJO.getString("store");
        String VIN = requestJO.getString("vin");
        Map param = MapUtil.mapper("dept", deptId, "VIN", VIN);//匹配商品参数
        //获取供应商平台报价商品
        JSONObject json = JSON.parseObject(invoke("sp.matching.lightningOffer", param));
        JSONArray body = json.getJSONArray("body");//供应商返回的数据
        Map<String,List<Object>> map = body.stream().collect(Collectors.groupingBy(item -> ((JSONObject)item).getJSONObject("product").getString("standardType")));
        Dept dept = deptRepository.findOne(deptId);
        String accessProvider = SpringManager.getBean(AccessProviderRepository.class).findByCompany(dept.getCompany().getId()).getId();//接入商
        //客户车辆信息
        List<FnCustomerExpand> fnCustomerExpands = getBean(FnCustomerExpandRepository.class).findAllByCarLicenseAndVendorCode(requestJO.getString("carLicense"), accessProvider);
        FnCustomerExpand fnCustomerExpand = fnCustomerExpands.stream().filter(item -> StringUtils.isNotEmpty(item.getJekunModelCode())).findFirst().get();
        JSONObject content = new JSONObject();
        JSONArray results = new JSONArray();
        map.forEach((k,v)->{
            JSONArray array =JSONArray.parseArray(JSON.toJSONString(v));
            Map result = getResult(array, dept, fnCustomerExpand);//按标准名称分类商品获取销售价格
            results.addAll((List)result.get("content"));//商品列表
        });
        content.put("item", results);

        Map priceForward = MapUtil.mapper("item", content);
        JSONArray newEnquiryItem = ((JSONObject)priceForward.get("item")).getJSONArray("item");
        Map enquiryItemMap = new HashMap();
        enquiryItemMap.put("results",change(newEnquiryItem, null, deptId));
        enquiryItemMap.put("enquiryID",requestJO.getString("id"));

        enquiryItemMap.put("CLXX",vehicleMessage(requestJO));
        enquiryItemMap.put("sign",false);
        return enquiryItemMap;
    }

    /**
     * 根据询价单获取车辆信息
     * @param requestJO
     * @return
     */
    public String vehicleMessage(JSONObject requestJO){
        JSONObject enquiry = JSONObject.parseObject(invoke("sp.enquiryService.findByID", requestJO).toString());
        JSONObject enquiryBody =  enquiry.getJSONObject("body");
        JSONObject response = JSONObject.parseObject(JSON.toJSONString(invoke("fn.api.getCustomerCarDetailInfoNotSession", enquiryBody)));
        String carModelLabel =  response.getString("carModelLabel")+"/"+response.getString("vin");
        return carModelLabel;
    }



    /**
     * 智选配件不匹配搜索供应商商品
     *
     * @param request 请求对象
     * @return
     */
    public Map suppInquireProduct(SimpleRequest request) {
        JSONObject param = request.getJO();
        JSONArray condition = param.getJSONArray("condition");
        JSONObject conditionModel = param.getJSONObject("conditionModel");
        String id = "";
        if (Objects.nonNull(conditionModel.getJSONObject("fixedLossDept"))) {
            id = conditionModel.getJSONObject("fixedLossDept").getString("id");
        }
        if (Objects.nonNull(conditionModel.getJSONObject("belongDept"))) {
            id = conditionModel.getJSONObject("belongDept").getString("id");
        }
        String keywords = "";
        String relationType="";
        for (Object o : condition) {
            JSONObject item = (JSONObject) o;
            if ("productTemp".equals(item.getString("field")))
                keywords = item.getString("value");
            if ("relationType".equals(item.getString("field")))
                relationType = item.getString("value");
        }
        //没有门店无查询价格前置商品
        if ("".equals(id) && !relationType.equals("yes")) return new HashMap();

        Dept dept = deptRepository.findOne(id);

        //根据配置车型ID+标准名称匹配商品
        if (StringUtils.isEmpty(keywords) )
            return MapUtil.mapper("type", "Whole", "content", new ArrayList<>());
        JSONObject json = JSON.parseObject(invoke("sp.matching.extendProduct", MapUtil.mapper("name", keywords)));
        JSONArray body = json.getJSONArray("body");
        FnCustomerExpand fnCustomerExpand = new FnCustomerExpand();
        if (Objects.isNull(conditionModel.getJSONObject("fnCustomerExpandTemp"))) {
            String carLiscence = conditionModel.getString("carLiscence");
            String vendorCode = conditionModel.getJSONObject("customer").getString("vendorCode");
            fnCustomerExpand = getFnCustomerExpand(carLiscence, vendorCode);
        } else {
            fnCustomerExpand = JSON.parseObject(conditionModel.getJSONObject("fnCustomerExpandTemp").toJSONString(), FnCustomerExpand.class);
        }


        spProductMap = new HashMap<>();
        this.platform = "zt";

        body = supplierGroup(body, dept);

        return getResult(body, dept, fnCustomerExpand);
    }


}
